package sfs

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/chicken-team-outside/chicken_transmission/driver"
	"github.com/golang/protobuf/proto"
	"go.uber.org/zap"
)

func (p *FsClient) RemoveAll(ctx context.Context, clientId uint64, paths []string) (*api_messages.PathsTaskResult, error) {
	r, err := p.sendRequest(ctx, clientId, api_messages.MessageType_RemoveAll, &api_messages.PathsMessage{
		Paths: paths,
	})
	if err == nil {
		result := new(api_messages.PathsTaskResult)
		err = proto.Unmarshal(r, result)
		if err == nil {
			return result, nil
		}
	}
	return nil, err
}

func (p *FsClient) removeAllProvider(ctx context.Context, header *api_messages.MessageHeader, data []byte) {
	if ctx.Err() == nil {
		query := new(api_messages.PathsMessage)
		err := proto.Unmarshal(data, query)
		var client driver.LocalDriver
		if err == nil {
			client = p.GetLocal()
			if client == nil {
				err = ErrNotSetLocalDriver
			}
		}
		result := new(api_messages.PathsTaskResult)
		if err == nil {
			for _, path := range query.Paths {
				err = client.Remove(path)
				if err != nil {
					result.Failed = append(result.Failed, &api_messages.PathsTaskError{
						Path:  path,
						Error: err.Error(),
					})
					zap.L().Warn("failed to remove path", zap.Error(err), zap.String("path", path))
				}
			}
			err = nil
		} else {
			result.Error = err.Error()
		}
		err = p.sendReplyByHeader(ctx, header, encodeStatusMessage(err))
		if err != nil {
			zap.L().Warn("error sending request", zap.Error(err), zap.Any("query", query), zap.Any("header", header))
		}
	}
}
